#!/bin/bash

# 检查是否提供了任意参数
if [ -n "$1" ]; then
    DELETE_ON_SUCCESS=true
else
    DELETE_ON_SUCCESS=false
fi

# 更新包列表
sudo apt update

# 安装通过包管理器安装 OpenCV 所需的依赖
sudo apt install -y libopencv-dev python3-opencv

# 验证 OpenCV 安装
python3 -c "import cv2; print(cv2.__version__)"

# 安装构建工具和所有的依赖软件包
sudo apt install -y build-essential cmake git pkg-config libgtk-3-dev \
    libavcodec-dev libavformat-dev libswscale-dev libv4l-dev \
    libxvidcore-dev libx264-dev libjpeg-dev libpng-dev libtiff-dev \
    gfortran openexr libatlas-base-dev python3-dev python3-numpy \
    libtbb2 libtbb-dev libdc1394-22-dev libopenexr-dev \
    libgstreamer-plugins-base1.0-dev libgstreamer1.0-dev

# 克隆 OpenCV 和 OpenCV contrib 源
mkdir -p ~/opencv_build && cd ~/opencv_build
git clone https://gitee.com/xu_panpan/opencv.git
git clone https://gitee.com/xu_panpan/opencv_contrib.git

# 进入 opencv 文件夹并新建 build 文件夹并切入
cd ~/opencv_build/opencv
mkdir -p build && cd build

# 使用 CMake 命令配置 OpenCV 构建
cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D INSTALL_C_EXAMPLES=ON \
    -D INSTALL_PYTHON_EXAMPLES=ON \
    -D OPENCV_GENERATE_PKGCONFIG=ON \
    -D OPENCV_EXTRA_MODULES_PATH=~/opencv_build/opencv_contrib/modules \
    -D BUILD_EXAMPLES=ON ..

# 编译 OpenCV
if make -j4; then
    # 安装 OpenCV
    sudo make install

    # 验证 OpenCV 安装版本
    pkg-config --modversion opencv4

    # 如果提供了任意参数，则删除 ~/opencv_build 文件夹及其内容
    if [ "$DELETE_ON_SUCCESS" == true ]; then
        rm -rf ~/opencv_build
        echo "编译成功，~/opencv_build 文件夹及其内容已删除。"
    fi
else
    echo "编译失败，不删除 ~/opencv_build 文件夹及其内容。"
fi